import webbrowser

import paramiko
import os
import subprocess
from constant import *

# 远程服务器信息
remote_server = prod_remote_server

# 本地和远程文件路径
work_dir = const_work_dir
local_jar_path = const_local_jar_path + remote_server['dist_name']
remote_jar_path = remote_server['remote_jar_path']

os.chdir(work_dir)
process = subprocess.run(stand_prod_remote_server['command'],
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         universal_newlines=True
                         )

print(f"命令输出:\n{process.stdout}")
if process.stderr:
    print(f"错误:\n{process.stderr}")

# 使用私钥进行SSH连接（如果有的话）
if remote_server['pkey']:
    private_key = paramiko.RSAKey.from_private_key_file(remote_server['pkey'])
else:
    private_key = None

# SSH连接到远程服务器
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(remote_server['host'],
            remote_server['port'],
            remote_server['username'],
            password=remote_server['password'],
            pkey=private_key
            )

# 使用SFTP上传dist目录下的所有文件到远程服务器
sftp = ssh.open_sftp()


def clear_remote_dir(remote_dir):
    try:
        files = sftp.listdir(remote_dir)
        for file in files:
            file_path = os.path.join(remote_dir,
                                     file
                                     )
            try:
                sftp.remove(file_path)
            except IOError:
                clear_remote_dir(file_path)
                sftp.rmdir(file_path)
    except FileNotFoundError:
        sftp.mkdir(remote_dir)


def upload_dir(local_dir, remote_dir):
    # 清空远程目录中的所有文件和子目录
    clear_remote_dir(remote_dir)

    for item in os.listdir(local_dir):
        local_path = os.path.join(local_dir,
                                  item
                                  )
        remote_path = os.path.join(remote_dir,
                                   item
                                   )

        if os.path.isdir(local_path):
            upload_dir(local_path,
                       remote_path
                       )
        else:
            sftp.put(local_path,
                     remote_path
                     )


upload_dir(local_jar_path,
           remote_jar_path
           )

sftp.close()
ssh.close()
webbrowser.open_new(remote_server['web_url'])

#
# # docker启动命令初次需要在服务器上执行： docker run -d --name vontron-warehouse --link mysql:mysql --link redis:redis -v /root/java/jar:/home/vh  -p 8080:8080 -m 1024m vontron-warehouse-java:1.0
# # 定义在远程服务器上执行的命令
# commands = [
#       f'cd {remote_jar_path} && pwd',  # 就是为了打印一下服务器的内容
#       f'docker restart vontron-warehouse || true',  # 停止已存在的容器
#
# ]
#
# # 在远程服务器上执行命令
# for cmd in commands:
#     stdin, stdout, stderr = ssh.exec_command(cmd)
#     output = stdout.read().decode()
#     error = stderr.read().decode()
#     if error:
#         print(f"错误: {error}")
#     else:
#         print(f"输出: {output}")
#     stdin.close()
# # 关闭SSH连接
# ssh.close()

print(f"部署完成，稍等一分钟后访问")
